package cn.winstone.scanner.impl;

import cn.winstone.enums.StatusCodeEnum;
import cn.winstone.scanner.ResourceScanner;
import cn.winstone.utils.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

/**
 * @author Winstone
 * @date 2020/7/28 - 7:44 下午
 */
public class ResourceScannerImpl implements ResourceScanner {
    private static String DEFAULT_RESOURCE = "index.html";
    private String baseUri;

    public ResourceScannerImpl(String baseUri) {
        this.baseUri = baseUri;
    }

    /**
     * 获取默认的Index.html
     *
     * @return
     * @throws FileNotFoundException
     */
    public InputStream getDefaultResource() throws FileNotFoundException {
        //获取文件夹下的所有文件位置
        List<String> filesURI = FileUtils.getFilesURI(baseUri);
        //查看是否有index.html
        for (String uri : filesURI) {
            if (uri.toLowerCase().contains(DEFAULT_RESOURCE)) {
                File file = new File(uri);
                InputStream stream = new FileInputStream(file);
                return stream;
            }
        }
        return null;
    }

    /**
     * 获取文件
     *
     * @param path
     * @return
     */
    public Object getResource(String path) {
        File file = new File(baseUri + path);

        try {
            InputStream stream = new FileInputStream(file);
            return stream;
        } catch (FileNotFoundException e) {
            return StatusCodeEnum.NOTFOUND;
        }
    }
}
